package com.nccsjz.back.link.dao;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import utils.DBUtils;

import com.nccsjz.base.BaseDAO;
import com.nccsjz.pojo.Link;

/**
 * LinkDAO类封装了与友情链接相关的数据访问操作
 * 
 * @author Administrator
 *
 */
public class LinkDAO extends BaseDAO {

	/**
	 * 
	 * @param con
	 */
	public LinkDAO(Connection con) {
		super(con);
		// TODO Auto-generated constructor stub
	}
	
	/**
	 * queryAll方法用于查询所有友情链接
	 * 
	 * @return List<Link>友情链接列表
	 * @throws SQLException 
	 */
	public List<Link> queryAll() throws SQLException{
		List<Link> links = new ArrayList<Link>();
		try{
			String sql = "select LINKID,LINKNAME,LINKHREF from FRIEND_LINKS order by LINKID desc";
			stmt = con.createStatement();
			rs = stmt.executeQuery(sql);
			while(rs.next()){
				Link link = new Link(rs.getLong(1),rs.getString(2),rs.getString(3));
				links.add(link);
			}
		}finally{
			DBUtils.CloseRs(rs);
			DBUtils.CloseStmt(stmt);
		}
		return links;
	}
	
	/**
	 * insertLink方法用于插入链接信息
	 * 
	 * @param link Link 链接对象
	 * @throws SQLException 
	 */
	public void insertLink(Link link) throws SQLException{
		try{
			String sql = "insert into FRIEND_LINKS (LINKNAME,LINKHREF) values (?,?)";
			pstmt = con.prepareStatement(sql);
			pstmt.setString(1, link.getTitle());
			pstmt.setString(2, link.getValue());
			pstmt.executeUpdate();
		}finally{
			DBUtils.CloseStmt(pstmt);
		}
	}
	
	/**
	 * queryLinkById方法根据编号查询链接信息
	 * 
	 * @param id Long 链接编号
	 * @return Link 链接对象
	 * @throws SQLException 
	 */
	public Link queryLinkById(Long id) throws SQLException{
		Link link = null;
		try{
			String sql = "select LINKNAME,LINKHREF from FRIEND_LINKS where LINKID = ?";
			pstmt = con.prepareStatement(sql);
			pstmt.setLong(1, id);
			rs = pstmt.executeQuery();
			if(rs.next()){
				link = new Link(id,rs.getString(1),rs.getString(2));
			}
		}finally{
			DBUtils.CloseRs(rs);
			DBUtils.CloseStmt(pstmt);
		}
		return link;
	}
	
	/**
	 * updateLink方法根据编号更新链接信息
	 * 
	 * @param link	Link 链接对象
	 * @throws SQLException
	 */
	public void updateLink(Link link) throws SQLException{
		try{
			String sql = "update FRIEND_LINKS set LINKNAME = ?,LINKHREF = ? where LINKID = ?";
			pstmt = con.prepareStatement(sql);
			pstmt.setString(1, link.getTitle());
			pstmt.setString(2, link.getValue());
			pstmt.setLong(3, link.getId());
			pstmt.executeUpdate();
		}finally{
			DBUtils.CloseStmt(pstmt);
		}
	}
	
	/**
	 * deleteLinkById方法根据编号删除友情链接信息
	 * 
	 * @param id Long 友情链接编号
	 * @throws SQLException
	 */
	public void deleteLinkById(Long id) throws SQLException{
		try{
			String sql = "delete from FRIEND_LINKS where LINKID = ?";
			pstmt = con.prepareStatement(sql);
			pstmt.setLong(1, id);
			pstmt.executeUpdate();
		}finally{
			DBUtils.CloseStmt(pstmt);
		}
	}

}
